package com.neusoft.neuiotms.dcom.repository.insurance.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.model.insurance.InsuranceRegister;
import com.neusoft.neuiotms.dcom.model.insurance.QInsuranceRegister;
import com.neusoft.neuiotms.dcom.repository.insurance.CustomizedInsuranceRegisterRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedInsuranceRegisterRepositoryImpl extends AbstractRepository
        implements CustomizedInsuranceRegisterRepository {

    @Override
    public List<InsuranceRegister> index(final Searchable searchable) {
        final QInsuranceRegister qInsuranceRegister = QInsuranceRegister.insuranceRegister;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<InsuranceRegister> query = this.query().selectFrom(qInsuranceRegister);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<InsuranceRegister> search(final Pageable pageable, final Searchable searchable) {
        final QInsuranceRegister qInsuranceRegister = QInsuranceRegister.insuranceRegister;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<InsuranceRegister> query = this.query().selectFrom(qInsuranceRegister);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return InsuranceRegister.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {

        final BooleanBuilder where = new BooleanBuilder();
        final QInsuranceRegister qInsuranceRegister = QInsuranceRegister.insuranceRegister;

        if (!StringUtils.isEmpty(searchable.getStrValue("code"))) {
            // 编码检索
            where.and(super.equalsStr(qInsuranceRegister.code, searchable, "code"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("remarks"))) {
            // 备注
            where.and(super.containsStr(qInsuranceRegister.remarks, searchable, "remarks"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("unitCode"))) {
            // 单位
            where.and(super.equalsStr(qInsuranceRegister.registerUnit.any().unitCode, searchable, "unitCode"));
        }

        if (null != searchable.getBooleanValue("releaseStatus")) {
            // 状态
            where.and(super.equalsBool(qInsuranceRegister.releaseStatus, searchable, "releaseStatus"));
        }

        return where;
    }

}
